package de.idgard.android.addon.ui.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import de.idgard.android.R;
import de.idgard.android.addon.js.ProfileSelection;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.json.response.PrivacyProfilesResponse;
import de.idgard.json.transport.Receiver;
import de.idgard.webapp.shared.dto.profile.SimpleProfileDto;

/**
 * @author pratik - Form login through IDGard.
 * 
 */
public class IDGPrivacyConnectLoginDialog extends Dialog {

	private Button btnOk;
	private Button btnCancel;

	private Spinner spinner;
	private ProfileSelection selection;

	public IDGPrivacyConnectLoginDialog(Context context, final PrivacyProfilesResponse list) {
		super(context);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.idgard_dialog_login_helper);

		String[] items = new String[list.size()];
		for (int i = 0; i < items.length; i++) {
			items[i] = list.get(i).getName();
		}
		ArrayAdapter<String> arr = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, items);
		btnOk = (Button) findViewById(R.id.btnLoginOk);
		btnCancel = (Button) findViewById(R.id.btnLoginCancel);
		spinner = (Spinner) findViewById(R.id.spinnerProfile);
		spinner.setAdapter(arr);

		btnCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismissWithSelection(ProfileSelection.cancel());
			}
		});
		btnOk.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final SimpleProfileDto p = list.get(spinner.getSelectedItemPosition());
				GlobalServiceRegistry.instance().getBackendService().getPrivacyConnectProfileToken(p.getId()).fire(new Receiver<String>() {
					@Override
					public void onSuccess(String token) {
						dismissWithSelection(ProfileSelection.selected(p.getUsername(), token));
					}
					@Override
					public void onFailure(int code, String response) {
						dismissWithSelection(ProfileSelection.cancel());
					}
					@Override
					public void onException(Exception e) {
						dismissWithSelection(ProfileSelection.cancel());
					}
				});
			}
		});
	}

	private void dismissWithSelection(ProfileSelection selection) {
		this.selection = selection;
		dismiss();
	}

	@Override
	public void onBackPressed() {
		dismissWithSelection(ProfileSelection.cancel());
	}

	/**
	 * @return the selection
	 */
	public ProfileSelection getSelection() {
		return selection;
	}
}
